package channel;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @ClassName MyServerSocketChannel
 * @Description
 * @Author lichuanqi
 * @Date 2021/12/11 10:18
 * @Version 1.0
 **/
public class MyServerSocketChannel {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(9090));
        MyServerSocketChannel myServerSocketChannel = new MyServerSocketChannel();
        while (true){
            System.out.println("等待连接》》》");
            SocketChannel socketChannel = serverSocketChannel.accept();
            System.out.println("接受连接："+socketChannel.getRemoteAddress().toString());
            myServerSocketChannel.handle(socketChannel);
        }
    }

    public void handle(SocketChannel socketChannel) throws IOException {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String remoteName = socketChannel.getRemoteAddress().toString();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    ByteBuffer sendBuffer = ByteBuffer.allocate(1024);
                    byte[] bytes = new byte[byteBuffer.remaining()];
                    while(true){
                        byteBuffer.clear();
                        socketChannel.read(byteBuffer);
                        byteBuffer.flip();
                        byteBuffer.get(bytes,0, byteBuffer.remaining());
                        String msg = new String(bytes);
                        System.out.println(remoteName+":"+msg);
                        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
                        String sendStr = reader.readLine();
                        byte[] bytes1 = sendStr.getBytes();
                        sendBuffer.clear();
                        sendBuffer.put(bytes1);
                        sendBuffer.flip();
                        socketChannel.write(sendBuffer);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    try {
                        socketChannel.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.start();
    }


}
